package com.javaweb.controller;

import com.javaweb.controller.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.javaweb.common.BusinessConstants.UPLOAD_DIR;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/13 9:31
 */

@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {

    @PostMapping("/upload")
    @ResponseBody
    public ResponseResult<String> upload(
            String username,
             MultipartFile file) {

        log.info("username: {}", username) ;
        // 处理文件上传逻辑
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                log.info("upload file name: {}", fileName)  ;

                // 设置文件上传路径
                File uploadFile = new File(UPLOAD_DIR + fileName);
                log.info("upload file: {}", uploadFile.getName()) ;
                // 创建目录（如果不存在）
                if (!uploadFile.getParentFile().exists()) {
                    uploadFile.getParentFile().mkdirs();
                }

                // 保存文件
                file.transferTo(uploadFile);
                return ResponseResult.ok("文件上传成功") ;
            } catch (IOException e) {
                log.error("文件上传失败：{}", e.getMessage());
            }
        } else {
            ResponseResult.error(HttpStatus.BAD_REQUEST, "文件为空");
        }
        return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "文件上传失败");

    }
}
